package com.cz.nongyetongv5.utils;

import android.content.Context;

import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.activity.LoginActivity;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.application.InitApplication;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.utils.HttpUtils.OnRequestExecuted;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * 下载数据的工具
 *
 * @author admin
 */
public class DownloadDataUtil {

    private static DownloadDataUtil downloadDataUtil = null;

    private String validateUserName;

    private String validatePassword;

    public void setValidateUserName(String validateUserName) {
        this.validateUserName = validateUserName;
    }

    public void setValidatePassword(String validatePassword) {
        this.validatePassword = validatePassword;
    }

    private DownloadDataUtil() {

    }

    /**
     * 获得新的实例
     *
     * @return
     */
    public static DownloadDataUtil getNewInstance() {

        if (downloadDataUtil == null) {
            downloadDataUtil = new DownloadDataUtil();
        }

        return downloadDataUtil;

    }

    /**
     * 当Login 结束的时候
     */
    public interface OnLoginEnd {

        /**
         * @param user      用户信息对象
         * @param stateCode 登陆的状态码
         */
        public void onLoginEnd(User user, int stateCode);

    }

    /**
     * 当下载完成后
     *
     * @author admin
     */
    public interface OnDownloadEnd {

        public void onDownloadEnd(List<Object> datas, int stateCode);

    }

    /**
     * 登陆
     *
     * @param username
     * @param password
     * @param url
     * @param context
     * @param loginEnd
     */
    public void login(final String username, final String password, String url,
                      final Context context, final OnLoginEnd loginEnd) {

        if (url != null && url.endsWith("/")) {
            url += username;

        } else if (url != null && !url.endsWith("/")) {
            url += "/" + username;
        }

        InitApplication application = (InitApplication) context
                .getApplicationContext();

        final String version = application.getVersion().getVersion();

        // 发送请求
        final HttpUtils httpUtil = HttpUtils.getInstance();

        // 增加回调函数
        httpUtil.setOnRequestExecuted(new OnRequestExecuted() {

            private User user = null;

            private Integer code = 200;

            @Override
            public void onRequestExecuted(int responseCode, String responseBody) {

                code = responseCode;

                // 如果状态编码为200
                if (responseCode == 200 && responseBody != null
                        && !"".equals(responseBody.toString().trim())) {

                    String json = responseBody.trim();
                    System.out.println(json);
                    try {
                        JSONObject jsonObject = new JSONObject(json);

                        // 拿到JSON中的status
                        String status = jsonObject.getString("status");

                        if (CommonConstants.serverIsOk(status)) {

                            String checkUserInfoURL = context
                                    .getResources()
                                    .getString(
                                            R.string.http_request_check_userinfo);

                            checkUserInfoURL = new ConfigUtil(context
                                    .getResources()).getPreHttpUrl()
                                    + checkUserInfoURL;

                            // 数据集合
                            JSONObject paramJson = new JSONObject();
                            paramJson.put("username", username);
                            paramJson.put("password", password);

                            paramJson.put("version", version);

                            httpUtil.setOnRequestExecuted(new OnRequestExecuted() {

                                @Override
                                public void onRequestExecuted(int responseCode,
                                                              String responseBody) {

                                    // 返回为200
                                    if (responseCode == 200
                                            && responseBody != null
                                            && !"".equals(responseBody
                                            .toString().trim())) {

                                        String json = responseBody.trim();
                                        System.out.println(json);
                                        try {
                                            JSONObject jsonObject = new JSONObject(
                                                    json);

                                            // 拿到JSON中的status
                                            String status = jsonObject
                                                    .getString("status");

                                            if (CommonConstants
                                                    .serverIsOk(status)) {

                                                String town_path_id = "";

                                                if (!jsonObject
                                                        .isNull("region_code_path")) {

                                                    town_path_id = jsonObject
                                                            .getString("region_code_path");
                                                }

                                                String showname = jsonObject
                                                        .getString("showname");

                                                // 最底层的地区的拼音
                                                String localPySimpleLastLocal = jsonObject
                                                        .getString("region_initials");

                                                String localPySimpleLocal = jsonObject
                                                        .getString("region_initials_path");

                                                String[] localSimpleArr = localPySimpleLocal
                                                        .split(",");

                                                String localPySimple = "";

                                                if (localSimpleArr.length == 4) {
                                                    localPySimple = localSimpleArr[2]
                                                            + localSimpleArr[3];
                                                } else if (localSimpleArr.length == 3) {
                                                    localPySimple = localSimpleArr[2];
                                                } else if (localSimpleArr.length == 2) {
                                                    localPySimple = localSimpleArr[1];
                                                } else {
                                                    localPySimple = localPySimpleLastLocal;
                                                }

                                                double region_longitude = jsonObject
                                                        .getDouble("region_longitude");
                                                double region_latitude = jsonObject
                                                        .getDouble("region_latitude");

                                                int region_zoom = jsonObject
                                                        .getInt("region_zoom");

                                                int is_tester = jsonObject
                                                        .getInt("is_tester");

                                                boolean tester = is_tester == 1 ? true
                                                        : false;

                                                String region_name=jsonObject.optString("region_name");
                                                String realName=jsonObject.optString("realname");

                                                user = new User(username,
                                                        password, town_path_id,
                                                        showname,
                                                        localPySimple,
                                                        region_longitude,
                                                        region_latitude,
                                                        region_zoom, tester,realName,region_name);

                                                // 登陆成功
                                                code = LoginActivity.LOGIN_SUCCESS;

                                            } else {
                                                // 用户名或者密码错误
                                                code = LoginActivity.USERINFO_ERROR;

                                                String message = jsonObject
                                                        .getString("error");

                                                user = new User();

                                                user.setMessage(message);

                                            }
                                        } catch (JSONException e) {
                                            // 通知信息锢示，服务器错误
                                            code = LoginActivity.SERVER_ERROR;

                                        }

                                    } else if (responseCode < 0) {
                                        // 通知信息锢示，没有网络
                                        code = LoginActivity.NO_NETWORK;
                                    } else {

                                        // 通知信息锢示，服务器错误
                                        code = LoginActivity.SERVER_ERROR2;
                                    }

                                }
                            });

                            // 咄行下一步操作,验证用户名和密码
                            httpUtil.sendRequest(checkUserInfoURL,
                                    paramJson.toString(), "post", "utf-8",
                                    validateUserName, validatePassword, null);
                        } else {
                            // 通知信息锢示,用户没有找到
                            code = LoginActivity.USER_UNDEFINED;
                        }
                    } catch (JSONException e) {
                        // 通知信息锢示,服务器发生错误
                        code = LoginActivity.SERVER_ERROR;

                    }
                } else if (responseCode < 0) {
                    // 通知信息锢示,发生异常没有网络
                    code = LoginActivity.NO_NETWORK;

                } else {
                    // 通知信息锢示,服务器发生错误
                    code = LoginActivity.SERVER_ERROR;
                }

                // 登陆完成后回调钩子函数
                loginEnd.onLoginEnd(user, code);

            }

        });

        httpUtil.sendRequest(url, null, "get", "UTF-8", validateUserName,
                validatePassword, null);

    }

}
